/*************************************************************************
 *
 * BeepTask
 * 
 * (c) Ales Povalac, alpov@alpov.net, http://www.alpov.net/
 * 
 *************************************************************************
 *
 * $Id: beep.c 107 2006-12-22 15:33:48Z alpov $
 * 
 *************************************************************************/         

#include <avr/io.h>
#include <avr/interrupt.h>
#include "../avrx/avrx.h"
#include "../avrx/AvrXFifo.h"
#include "hw.h"
#include "beep.h"
#include "button.h"

MessageControlBlock BeepOnce, BeepStart, BeepStop;
MessageQueue BeepQueue;
TimerMessageBlock BeepStopTimer;
TimerControlBlock BeepDelayTimer;


/*************************************************************************
 * inicializace tasku
 *************************************************************************/ 
void InitBeepTask(void)
{
    OCR2 = F_CPU/(2*8*BEEP_FREQ);
    TCCR2 = _BV(WGM21) | _BV(CS21) | _BV(COM20);
    Beep(0);
}


/*************************************************************************
 * uloha BeepTask
 * min. stack 2B 
 *************************************************************************/ 
AVRX_GCC_TASKDEF(BeepTask, 5, 3)
{
    MessageControlBlock *msg;
    
    while (1) {
        msg = AvrXWaitMessage(&BeepQueue);
        if (msg == &BeepOnce) {
            BackLight(1);
            Beep(1);
            AvrXDelay(&BeepDelayTimer, BEEP_ONCE_LEN);
            Beep(0);
            BackLightTimer();
            
        } else if (msg == &BeepStart) {
            AvrXStartTimerMessage(&BeepStopTimer, BEEP_TIMEOUT, &BeepQueue);
            BackLight(1);
            
            while (1) {
                msg = AvrXRecvMessage(&BeepQueue);
                if (msg == &BeepStart) {
                    AvrXCancelTimerMessage(&BeepStopTimer, &BeepQueue);
                    AvrXStartTimerMessage(&BeepStopTimer, BEEP_TIMEOUT, &BeepQueue);

                } else if ((msg == &BeepStop) || ((pTimerMessageBlock)msg == &BeepStopTimer)) {
                    BackLightTimer();
                    AvrXCancelTimerMessage(&BeepStopTimer, &BeepQueue);
                    break;

                } else if ((msg == &BeepOnce) || (msg == NOMESSAGE)) {
                    Beep(1);
                    AvrXDelay(&BeepDelayTimer, BEEP_ON_LEN);
                    Beep(0);
                    AvrXDelay(&BeepDelayTimer, BEEP_OFF_LEN);
                }
            }    

        }
    }
}

